package com.ciaojian.core.service;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ciaojian.core.mapper.DistRecordMapper;
import com.ciaojian.core.mapper.DistUserMapper;
import com.ciaojian.core.model.DistRecord;
import com.ciaojian.core.model.DistUser;
import com.ciaojian.core.model.vo.DistUserVo;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * @author oxiny
 */
public abstract class DistUserService<M extends BaseMapper<T>, T> extends ServiceImpl<DistUserMapper, DistUser> {
    @Resource
    DistRecordService<DistRecordMapper, DistRecord> distRecordService;

    /**
     * 查询用户是否可以成为分销员
     *
     * @param userId 用户
     * @return 已成为返回TRUE
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean checkByTargetId(Integer userId) {
        return this.baseMapper.selectById(userId) == null;
    }

    /**
     * 申请成为分销员
     *
     * @param userId 用户ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void apply(Integer userId) {
        Assert.isTrue(this.checkByTargetId(userId), "您暂不可成为分销员");

        // 查找被分销记录
        DistRecord distRecord = distRecordService.lambdaQuery()
                .eq(DistRecord::getTargetId, userId).one();
        DistUserVo parent;
        // 查找父级分销员信息
        if (distRecord == null) {
            parent = new DistUserVo().setUserId(0).setDistGroupId(1);
        } else {
            parent = this.baseMapper.findByUserId(distRecord.getDistId());
        }

        new DistUser()
                .setUserId(userId)
                .setDistGroupId(parent.getDistGroupId())
                .setParentId(parent.getUserId())
                .insert();
    }
}
